package com.pachiraframework.springcloud.rabbitmq.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.pachiraframework.springcloud.rabbitmq.domain.Book;


@RestController
public class Controller {

	
	@Autowired
	RabbitTemplate rabbitTemplate;
	
	@Autowired
	AmqpAdmin amqpAdmin;
	
	
	/**
	 * localhost:20001/createExchange
	 * @return
	 */
	@GetMapping("/createExchange")
	public String createExchange(){
		
//		Exchange exchange = new DirectExchange("amqpadmin.exchange");
//		amqpAdmin.declareExchange(exchange);
//		System.out.println("创建完成");
		
		
//		amqpAdmin.declareQueue(new Queue("amqpadmin.queue",true));
		
		
		//创建绑定规则
//		amqpAdmin.declareBinding(new Binding("amqpadmin.queue", Binding.DestinationType.QUEUE
//				, "amqpadmin.exchange", "amqp.haha", null));
		
		
		
		
		return "ok";
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/**
	 * localhost:20001/diantodian
	 * 1，单播
	 * 点对点的发送消息
	 * @return
	 */
	@GetMapping("/diantodian")
	public String diantodian() {
//		message需要自己构造一个：定义消息体的内容和头
//		rabbitTemplate.send(exchange, routingKey, message);
		
//		object默认当成消息体，只需要传入要发送的对象，自动序列化发送给rabbitmq
//		rabbitTemplate.convertAndSend(exchange, routingKey, object);
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("msg", "这是第一个消息");
		map.put("data", Arrays.asList("helloworld",123,true));
		//对象默认是序列化以后发送
		rabbitTemplate.convertAndSend("exchange.direct","atguigu.news",new Book("asa", 9.9));
		
		
		
		return "ok";
	}
	
	
	
	/**
	 * localhost:20001/received
	 * 收数据，如何将数据自动的转为json发送出去
	 * @return
	 */
	@GetMapping("/received")
	public String received() {
		
		Message receive = rabbitTemplate.receive("atguigu.news");
		if (receive!=null) {
			System.out.println(receive.getClass());
			System.out.println(receive);
			
		}
		
		
		return "ok";
	}
	
	
	
	
	/**
	 * localhost:20001/sendmessage
	 * 广播
	 */
	@GetMapping("/sendmessage")
	public String sendmessage(){
		
		rabbitTemplate.convertAndSend("exchange.fanout","",new Book("asb", 9.8));
		
		
		return "ok";
	}
	
	
	
	
	
	
	
}
